﻿using System;
using System.Collections.Generic;

namespace BowlingGame
{
    public class Game
    {
        public Int32 Score
        {
            get { return GetScoreForFrame(_currentFrame); }
        }

        public void AddThrow(Int32 pins)
        {
            _balls.Add(pins);

            if (_currentFrame == 9)
                return;

            if (_balls.Count % 2 == 1 && pins == 10)
                _currentFrame++;
            else if (_balls.Count % 2 == 0)
                _currentFrame++;
        }

        private readonly IList<Int32> _balls = new List<Int32>();

        private Int32 GetBallScore(Int32 ballIndex)
        {
            return ballIndex < _balls.Count ? _balls[ballIndex] : 0;
        }

        public Int32 GetScoreForFrame(Int32 frameIndex)
        {
            var score = 0;
            var ballIndex = 0;

            for (var i = 0; i <= frameIndex; i++)
            {
                var ballScore = GetBallScore(ballIndex++);

                if (ballScore == 10)
                    score += ballScore + GetBallScore(ballIndex) + GetBallScore(ballIndex + 1);
                else
                {
                    ballScore += GetBallScore(ballIndex++);

                    if (ballScore == 10)
                        ballScore += GetBallScore(ballIndex);

                    score += ballScore;
                }
            }

            return score;
        }

        public Int32 CurrentFrameIndex
        {
            get { return _currentFrame; }
        }
        private Int32 _currentFrame;
    }
}